#!/usr/bin/env python3
"""
启动扩展功能服务器
包含AI分析、任务管理、设备管理、数据导出等功能
"""
import os
import sys
import subprocess
import logging
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def check_dependencies():
    """检查依赖项"""
    try:
        import fastapi
        import uvicorn
        import pandas
        import numpy
        import sklearn
        import openpyxl
        logger.info("✅ 所有依赖项已安装")
        return True
    except ImportError as e:
        logger.error(f"❌ 缺少依赖项: {e}")
        logger.info("请运行: pip install -r requirements_extended.txt")
        return False

def install_dependencies():
    """安装依赖项"""
    requirements_file = Path(__file__).parent / "requirements_extended.txt"
    
    if not requirements_file.exists():
        logger.error(f"❌ 依赖文件不存在: {requirements_file}")
        return False
    
    try:
        logger.info("📦 安装依赖项...")
        subprocess.run([
            sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
        ], check=True)
        logger.info("✅ 依赖项安装完成")
        return True
    except subprocess.CalledProcessError as e:
        logger.error(f"❌ 依赖项安装失败: {e}")
        return False

def create_requirements_file():
    """创建扩展功能依赖文件"""
    requirements_content = """# 扩展功能依赖项
fastapi>=0.104.0
uvicorn[standard]>=0.24.0
pydantic>=2.0.0
pandas>=2.0.0
numpy>=1.24.0
scikit-learn>=1.3.0
openpyxl>=3.1.0
python-multipart>=0.0.6
python-jose[cryptography]>=3.3.0
passlib[bcrypt]>=1.7.4
python-dotenv>=1.0.0
pymssql>=2.2.0
"""
    
    requirements_file = Path(__file__).parent / "requirements_extended.txt"
    
    try:
        with open(requirements_file, 'w', encoding='utf-8') as f:
            f.write(requirements_content)
        logger.info(f"✅ 创建依赖文件: {requirements_file}")
        return True
    except Exception as e:
        logger.error(f"❌ 创建依赖文件失败: {e}")
        return False

def start_server():
    """启动服务器"""
    try:
        logger.info("🚀 启动扩展功能服务器...")
        logger.info("📡 服务器地址: http://localhost:8886")
        logger.info("📚 API文档: http://localhost:8886/docs")
        logger.info("🔧 功能列表: http://localhost:8886/api/v2/features")
        logger.info("💡 按 Ctrl+C 停止服务器")
        
        # 启动服务器
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "app.main_extended:app",
            "--host", "0.0.0.0",
            "--port", "8886",
            "--reload",
            "--log-level", "info"
        ])
        
    except KeyboardInterrupt:
        logger.info("🛑 服务器已停止")
    except Exception as e:
        logger.error(f"❌ 服务器启动失败: {e}")

def main():
    """主函数"""
    logger.info("=" * 60)
    logger.info("4G信号检测系统 - 扩展功能服务器")
    logger.info("=" * 60)
    
    # 检查Python版本
    if sys.version_info < (3, 7):
        logger.error("❌ 需要Python 3.7或更高版本")
        sys.exit(1)
    
    logger.info(f"🐍 Python版本: {sys.version}")
    
    # 创建依赖文件
    if not Path(__file__).parent.joinpath("requirements_extended.txt").exists():
        logger.info("📝 创建依赖文件...")
        if not create_requirements_file():
            sys.exit(1)
    
    # 检查依赖项
    if not check_dependencies():
        logger.info("📦 尝试安装依赖项...")
        if not install_dependencies():
            sys.exit(1)
    
    # 启动服务器
    start_server()

if __name__ == "__main__":
    main()